package com.foreknow.tijian.service.Impl;

import com.foreknow.tijian.dao.UsersDao;
import com.foreknow.tijian.dao.Impl.UsersDaoImpl;
import com.foreknow.tijian.po.Users;
import com.foreknow.tijian.service.UsersService;
import com.foreknow.tijian.util.DBUtil;

import java.sql.SQLException;

public class UsersServiceImpl implements UsersService {

    @Override
    public Users getUsersByUserIdByPass(String userId, String password) {
        Users users = null;
        UsersDao usersDao = new UsersDaoImpl();
        try{
            users=usersDao.getUsersByUserIdByPass(userId,password);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally{
            DBUtil.close();
        }
        return users;
    }

    @Override
    public Users getUsersById(Users users) {
        Users result ;
        UsersDao usersDao = new UsersDaoImpl();
        try {
            result = usersDao.getUsersById(users);
        }  catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            DBUtil.close();
        }
        return result;
    }

    @Override
    public int saveUsers(Users users) {
        int result = 0;
        UsersDao usersDao = new UsersDaoImpl();
        try {
            //开始事务
            DBUtil.beginTransaction();
            result = usersDao.saveUsers(users);
            //提交事务
            DBUtil.commitTransaction();
        }  catch (Exception e) {
            try {
                //取消之前的所有操作
                DBUtil.rollbackTransaction();
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
            throw new RuntimeException(e);
        }finally {
            DBUtil.close();
        }
        return result;
    }
}
